package cn.qicaiwang.open.system.utils;

import cn.hutool.core.util.StrUtil;
import cn.qicaiwang.open.common.annotation.Dict;
import cn.qicaiwang.open.system.model.entity.SystemDictItem;
import cn.qicaiwang.open.system.service.ISystemDictItemService;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author GAOXI
 * @Date:2025/5/18
 * @Description:
 * @version：1.0
 **/
public class DictUtil {

//    private static Map<String, List<SystemDictItem>> cacheMap =new HashMap<>();

    public static ThreadLocal<Map<String, List<SystemDictItem>>> cacheMap=new ThreadLocal<>();

    public static void transition(ISystemDictItemService service,Object obj) throws Exception {
        Field[] fields = obj.getClass().getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            field.setAccessible(true);
            System.out.println(field);

            Dict annotation = field.getAnnotation(Dict.class);

            if (annotation != null) {
                Object o = field.get(obj);
                if (o == null || StrUtil.isBlank(o.toString())) {
                    continue;
                }
                //查数据库获取字典
                if (StrUtil.isNotBlank(annotation.type())) {

                    boolean b= false;
                    Map<String, List<SystemDictItem>> map1 = cacheMap.get();



                    if (cacheMap.get()!=null){
                        b = cacheMap.get().containsKey(annotation.type());
                    }else {
                        Map<String, List<SystemDictItem>> map = new HashMap<>();
                        cacheMap.set(map);
                    }

                    List<SystemDictItem> dictItems = null;

                    if (!b) {
                        dictItems = service.selectListByDictType(annotation.type());
                        cacheMap.get().put(annotation.type(), dictItems);
                    } else {
                        dictItems = cacheMap.get().get(annotation.type());
                    }
                    dictItems.forEach(x -> {
                        if (x.getK().equals(o.toString())) {
                            try {
                                field.set(obj, x.getV());
                            } catch (IllegalAccessException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    });


                }

            }
        }


    }


}
